#!/bin/python3
"""Build FRCMake Project"""
import shutil
import sys
import os

if sys.argv[2] is None:
    # If no arguments are supplied print usage and exit
    print("Usage: build.sh <Native | RoboRIO> <Debug | Release>")
    sys.exit(1)
elif sys.argv[1] == "help":
    print("""
        Usage: build.sh <Native | RoboRIO> <Debug | Release>

        Build targets:
        - Native: Use systems default compiler and wpilib install (Unimplemented)
        - RIO: Use RoboRIO cross compiler and RoboRIO wpilib libraries (Linux only)

        Build types:
        - Debug: Enables CMake debug flag
        - Release: Enables CMake release flag
        """)
    sys.exit(0)

build_target=sys.argv[1]
build_type=sys.argv[2]

# Ensure output directory exist
mkdir -p "$ProjRoot"/output/"$BuildTarget"/"$BuildType"

# Install Conan packages
if build_target == "RoboRIO":
    conan install ./build/conan -if "$ProjRoot"/output/"$BuildTarget"/"$BuildType"/conan --build missing --profile "$ProjRoot"/build/conan/roborio.ini -s build_type="$BuildType"
    rio="ON"
elif build_target == "Native":
    conan install ./build/conan -if "$ProjRoot"/output/"$BuildTarget"/"$BuildType"/conan --build missing -s build_type="$BuildType"
    rio="OFF"

# Call CMake to build project
cmake -S "$ProjRoot" -B "$ProjRoot"/output/"$BuildTarget"/"$BuildType"/ -DCMAKE_BUILD_TYPE="$BuildType" -DCMakeRIO="$RIO"

# Compile output
cmake --build "$ProjRoot"/output/"$BuildTarget"/"$BuildType"/ --config "$BuildType" --parallel

# Link compile_commands.json for clangd language server functionality
[ -f "$ProjRoot"/compile_commands.json ] && rm compile_commands.json
mv "$ProjRoot"/output/"$BuildTarget"/"$BuildType"/compile_commands.json "$ProjRoot"
